import json
import os
import re
import sys
from PyQt5 import uic
from PyQt5.QtCore import QThread, pyqtSignal, QObject, QUrl
from PyQt5.QtGui import QTextCursor, QDesktopServices
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
from qt_material import apply_stylesheet

from change_config import read_json, ChangeConfig, write_json, OpenPro, InstallPnpm, GitCheck

init_para = read_json("init.json", "./")
combox_text = {
    "星选新客云": "wxf304b2b1daaae783",
    "哈夫": "wx3c1883ba26190de5",
    "小鹅（伴伴）": "wx49878335f1e732ea"
}


# @colorful('default')
class MyApp(QMainWindow):
    def __init__(self):
        super().__init__()
        uic.loadUi("untitled.ui", self)
        sys.stdout = SignalCmd()
        sys.stdout.text_update.connect(self.updatetext)
        # self.ui.show()
        # print(self.ui)

        self.lineEdit_4.setText(init_para['pro_path'])
        self.lineEdit_5.setText(init_para['tool_path'])
        self.pushButton.clicked.connect(self.select_dir)
        self.pushButton_2.clicked.connect(self.select_dir)
        self.lineEdit_6.setText(init_para['extAppid'])
        self.comboBox.setCurrentIndex(init_para['extAppid_index'])
        self.comboBox_2.setCurrentIndex(init_para['app_js_index'])
        self.comboBox_3.setCurrentIndex(init_para['config_js_index'])
        self.pushButton_8.clicked.connect(self.clear_cmd)
        self.pushButton_5.clicked.connect(self.modify_pro_code)
        self.comboBox.currentIndexChanged.connect(self.indexchange)
        self.pushButton_6.clicked.connect(self.start_dev_tool)
        self.pushButton_7.clicked.connect(self.install_pnpm)
        self.pushButton_3.clicked.connect(lambda: self.git_operation("get_branch"))
        self.pushButton_4.clicked.connect(lambda: self.git_operation("switch_branch"))

    def updatetext(self, text):
        """
            更新textBrowser
        """
        cursor = self.textBrowser.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.textBrowser.append(text)
        self.textBrowser.setTextCursor(cursor)
        self.textBrowser.ensureCursorVisible()
        # if "..成功" in text and self.interval != 0:
        #     self.value += 1
        #     percent = int(self.value / self.progressBar_count * 100)
        #     self.progressBar.setValue(percent)
        # elif "--成功" in text and self.interval != 0:
        #     self.value += 1
        #     percent = int(self.value / self.progressBar_count * 100)
        #     self.progressBar_2.setValue(percent)
        # elif text == "执行完毕":
        #     self.progressBar.setValue(100)
        #     self.progressBar_count = 0
        #     self.interval = 0
        #     self.value = 0
        # elif text == "请求完毕":
        #     self.progressBar_2.setValue(100)
        #     self.progressBar_count = 0
        #     self.interval = 0
        #     self.value = 0

    def modify_pro_code(self):
        app_js_list = ["develop", "trial", "release"]
        config_js_list = ["dev", 'test', 'pro']
        pro_path = self.lineEdit_4.text()
        tool_path = self.lineEdit_5.text()
        extAppid = self.lineEdit_6.text()
        app_js_env = app_js_list[int(self.comboBox_2.currentIndex())]
        config_js_env = config_js_list[int(self.comboBox_3.currentIndex())]
        savedata = {
            "pro_path": pro_path,
            "tool_path": tool_path,
            "extAppid_index": self.comboBox.currentIndex(),
            "extAppid": extAppid,
            "app_js_index": self.comboBox_2.currentIndex(),
            "config_js_index": self.comboBox_3.currentIndex()
        }
        try:
            self.modify = ModifyCodeThread(pro_path, extAppid, app_js_env, config_js_env, savedata)
            self.modify.sinOut.connect(self.result_msgbox)
            self.modify.start()
            # self.statusBar().showMessage("导出完成")
            self.pushButton_5.setEnabled(False)
        except Exception as e:
            print(e, end='')

    def start_dev_tool(self):
        pro_path = self.lineEdit_4.text()
        tool_path = self.lineEdit_5.text()
        try:
            self.dev_tool = StartDevToolThread(pro_path, tool_path)
            self.dev_tool.sinOut.connect(self.result_msgbox)
            self.dev_tool.start()
            # self.statusBar().showMessage("导出完成")
            self.pushButton_6.setEnabled(False)
        except Exception as e:
            print(e, end='')

    def install_pnpm(self):
        pro_path = self.lineEdit_4.text()
        try:
            self.pnpm = InstallPnpmThread(pro_path)
            self.pnpm.sinOut.connect(self.result_msgbox)
            self.pnpm.start()
            # self.statusBar().showMessage("导出完成")
            self.pushButton_7.setEnabled(False)
        except Exception as e:
            print(e, end='')

    def git_operation(self, func):
        pro_path = self.lineEdit_4.text()
        branch = self.lineEdit_7.text()
        newbranch = self.lineEdit_8.text()
        try:
            self.git = GitOperationThread(pro_path, branch, newbranch, func)
            self.git.sinOut.connect(self.result_msgbox)
            self.git.start()
            # self.statusBar().showMessage("导出完成")
        except Exception as e:
            print(e, end='')

    def indexchange(self):
        key = self.comboBox.currentText()
        self.lineEdit_6.setText(combox_text[key])

    def debug_question_msgbox(self):
        msg_result = QMessageBox.question(self, "执行提示", f"当前执行环境非测试环境\n请仔细确认参数无误后执行！\n参数是否已经确认完毕？",
                                          QMessageBox.Yes | QMessageBox.No)
        if msg_result == QMessageBox.Yes:
            return True
        else:
            return False

    def result_msgbox(self, str):
        sender_name = self.sender().__class__.__name__
        if sender_name == "ModifyCodeThread":
            if str == "修改成功":
                print("ModifyCodeThread：修改成功", end='')
                QMessageBox.information(self, "修改成功", f"已经成功对{self.lineEdit_4.text()}项目进行修改", QMessageBox.Close)
                self.pushButton_5.setEnabled(True)
            else:
                QMessageBox.critical(self, "修改失败", str, QMessageBox.Close)
                self.pushButton_5.setEnabled(True)
        elif sender_name == "StartDevToolThread":
            if str == "启动成功":
                print("StartDevToolThread：启动成功", end='')
                QMessageBox.information(self, "启动成功", f"已经成功发出启动{self.lineEdit_4.text()}项目命令", QMessageBox.Close)
                self.pushButton_6.setEnabled(True)
            else:
                QMessageBox.critical(self, "启动失败", str, QMessageBox.Close)
                self.pushButton_6.setEnabled(True)
        elif sender_name == "InstallPnpmThread":
            if str == "安装成功":
                print("InstallPnpmThread：安装成功", end='')
                QMessageBox.information(self, "安装成功", f"已经成功为{self.lineEdit_4.text()}项目安装依赖", QMessageBox.Close)
                self.pushButton_7.setEnabled(True)
            else:
                QMessageBox.critical(self, "安装失败", str, QMessageBox.Close)
                self.pushButton_7.setEnabled(True)
        elif sender_name == "GitOperationThread":
            if str == "获取成功":
                print("GitOperationThread：获取成功", end='')
                QMessageBox.information(self, "获取成功", f"已经获取当前分支，请查看控制台", QMessageBox.Close)
            elif str == "切换成功":
                print("GitOperationThread：切换成功", end='')
                QMessageBox.information(self, "切换成功", f"已经成功切换到{self.lineEdit_8.text()}分支", QMessageBox.Close)
            else:
                QMessageBox.critical(self, "安装失败", str, QMessageBox.Close)
                self.pushButton_7.setEnabled(True)

    def clear_cmd(self):
        self.textBrowser.clear()

    def change_tab(self):
        sender = self.sender()
        if sender.text() == "page":
            index = 0
        else:
            index = 1
        self.stackedWidget.setCurrentIndex(index)

    def select_dir(self):
        dir_name = QFileDialog.getExistingDirectory(self, "选择目录")
        if os.sep not in dir_name:
            dir_name = dir_name.replace("/", os.sep)
        sender = self.sender().objectName()
        if dir_name:
            if sender == "pushButton":
                self.lineEdit_4.setText(dir_name)
            elif sender == "pushButton_2":
                self.lineEdit_5.setText(dir_name)

    def switch_themes(self):
        sender_text = self.sender().text()
        if sender_text == "系统原生":
            print("切换系统原生成功，重新启动生效！")
        else:
            apply_stylesheet(App, theme=f'{sender_text}.xml')
        write_json({"theme": sender_text}, f"{BASE_PATH + os.sep}icon/current_theme.json", abs_path=True)

    def shut_down_thread(self):
        sender = self.sender().objectName()
        if sender == "pushButton_17" and self.smoke:
            self.smoke.stop()
            print(f"{self.smoke}已经停止！")
            self.pushButton_11.setEnabled(True)
        if sender == "pushButton_22" and self.design_run:
            self.design_run.stop()
            print(f"{self.design_run}已经停止！")
            self.pushButton_21.setEnabled(True)


class ModifyCodeThread(QThread):
    sinOut = pyqtSignal(str)
    result_signal = pyqtSignal(str, str)

    def __init__(self, pro_path, ext_appid, app_js_env, config_js_env, savedata):
        super(ModifyCodeThread, self).__init__()
        self.change = ChangeConfig(pro_path)
        self.pro_path = pro_path
        self.ext_appid = ext_appid
        self.app_js_env = app_js_env
        self.config_js_env = config_js_env
        self.savedata = savedata

    def run(self) -> None:
        write_json(self.savedata, 'init.json', './')
        try:
            self.change.change_ext_json(self.ext_appid)
            self.change.change_app_js(self.app_js_env)
            self.change.change_config_js(self.config_js_env)
            self.change.change_api_base_config_js(self.config_js_env)
            self.sinOut.emit("修改成功")
            # self.result_signal.emit(self.save_filename, "smoke")
        except Exception as e:
            print(e, end='')
            self.sinOut.emit(str(e))


class StartDevToolThread(QThread):
    sinOut = pyqtSignal(str)
    result_signal = pyqtSignal(str, str)

    def __init__(self, pro_path, tool_path):
        super(StartDevToolThread, self).__init__()
        self.dev = OpenPro(pro_path, tool_path)
        self.pro_path = pro_path
        self.tool_path = tool_path

    def run(self) -> None:
        try:
            self.dev.open_pro()
            self.sinOut.emit("启动成功")
            # self.result_signal.emit(self.save_filename, "smoke")
        except Exception as e:
            print(e, end='')
            self.sinOut.emit(str(e))


class InstallPnpmThread(QThread):
    sinOut = pyqtSignal(str)
    result_signal = pyqtSignal(str, str)

    def __init__(self, pro_path):
        super(InstallPnpmThread, self).__init__()
        self.pnpm = InstallPnpm(pro_path)
        self.pro_path = pro_path

    def run(self) -> None:
        try:
            self.pnpm.install()
            self.sinOut.emit("安装成功")
            # self.result_signal.emit(self.save_filename, "smoke")
        except Exception as e:
            print(e, end='')
            self.sinOut.emit(str(e))


class GitOperationThread(QThread):
    sinOut = pyqtSignal(str)
    result_signal = pyqtSignal(str, str)

    def __init__(self, pro_path, branch, newbranch, func):
        super(GitOperationThread, self).__init__()
        self.git = GitCheck(pro_path)
        self.pro_path = pro_path
        self.branch = branch
        self.newbranch = newbranch
        self.func = func

    def run(self) -> None:
        try:
            if self.func == 'get_branch':
                self.git.git_get_current_branch()
                self.sinOut.emit("获取成功")
            elif self.func == 'switch_branch':
                self.git.git_change_branch(self.branch, self.newbranch)
                self.sinOut.emit("切换成功")
            # self.result_signal.emit(self.save_filename, "smoke")
        except Exception as e:
            print(e, end='')
            self.sinOut.emit(str(e))


class SignalCmd(QObject):
    text_update = pyqtSignal(str)

    def write(self, text):
        self.text_update.emit(str(text))
        # loop = QEventLoop()
        # QTimer.singleShot(100, loop.quit)
        # loop.exec_()
        QApplication.processEvents()


if __name__ == '__main__':
    App = QApplication(sys.argv)
    # theme = read_json(f"{BASE_PATH + os.sep}icon/current_theme.json", abs_path=True)["theme"]
    # if theme != "系统原生":
    apply_stylesheet(App, theme=f'dark_cyan.xml')
    stats = MyApp()
    # main_window = CandyWindow.createWindow(stats, "blueGreen", title="GDOS助手", ico_path="./icon/g1.ico")
    # main_window.show()
    stats.show()
    sys.exit(App.exec_())
